package com.tony.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: ReentrantLockDemo001
 * @Auther: 皮蛋布丁
 * @Date: 2022/04/09/17:43
 * @Description: 互斥锁
 */
public class ReentrantLockDemo001 {

    public static void main(String[] args) {

        ReentrantLockTicket ticket = new ReentrantLockTicket(); //共享一个售票应用
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                ticket.sale();
            },"售票员_" + i).start();
        }

    }
}
class ReentrantLockTicket { //实现抢票的处理机制
    private int count = 3;//总票数
    private Lock lock = new ReentrantLock();//定义互斥锁
    public void sale() { //售票处理
        this.lock.lock(); //对当前的线程锁定
        try {
            if (this.count > 0) { //【业务处理1】判断今年是否有剩余的票数
                //在进行操作延迟的过程之中，独占锁始终锁定当前的资源
                TimeUnit.SECONDS.sleep(1);
                System.out.printf("【%s】卖票，剩余票数：%d%n",Thread.currentThread().getName(),this.count--);
            } else {
                System.out.printf("【%s】票已经卖完了，明天请早！%n",Thread.currentThread().getName());
            }

        } catch (Exception e) {}
        finally {
            this.lock.unlock(); //进行解锁配置
        }

    }

}
